package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.R;
import com.example.domain.Movie;
import com.example.domain.MovieCategory;
import com.example.domain.model.MovieDTO;
import com.example.domain.model.MyPage;
import com.example.domain.model.SearchDTO;
import com.example.mapper.MovieCategoryMapper;
import com.example.mapper.MovieMapper;
import com.example.service.MovieService;
import com.example.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;


@Slf4j
@Api(tags = "电影管理")
@RestController
@RequestMapping("/movie")
public class MovieController {

    @Value("${upload.moviePath}")
    private String uploadMoviePath;

    @Value("${upload.actorPath}")
    private String uploadActorPath;
    @Autowired
    private MovieService movieService;

    @Autowired
    private MovieMapper movieMapper;

    @Autowired
    private MovieCategoryMapper movieCategoryMapper;

    @ApiOperation(value = "电影列表")
    @PostMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页索引", defaultValue = "1"),
            @ApiImplicitParam(name = "size", value = "每页显示记录数", defaultValue = "20")
    })
    public R<IPage<MovieDTO>> getSearchList(@RequestBody SearchDTO searchDTO){
        Page page = new Page(searchDTO.getCurrent(), searchDTO.getSize());
        return R.success(movieService.getList(page,searchDTO));
    }

    @ApiOperation(value = "最新电影列表")
    @PostMapping("/newList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页索引", defaultValue = "1"),
            @ApiImplicitParam(name = "size", value = "每页显示记录数", defaultValue = "20")
    })
    public R<IPage<MovieDTO>> getNewList(@RequestBody MyPage mypage){
        Page page = new Page(mypage.getCurrent(), mypage.getSize());
        return R.success(movieService.getNewList(page));
    }
    @ApiOperation(value = "热门电影列表")
    @PostMapping("/hotList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页索引", defaultValue = "1"),
            @ApiImplicitParam(name = "size", value = "每页显示记录数", defaultValue = "20")
    })
    public R<IPage<MovieDTO>> getHotList(@RequestBody MyPage mypage){
        Page page = new Page(mypage.getCurrent(), mypage.getSize());
        return R.success(movieService.getHotList(page));
    }



    @ApiOperation(value = "搜索电影")
    @PostMapping("/search")
    public R<IPage<MovieDTO>> getList(@RequestBody SearchDTO searchDTO){
        List<MovieCategory> movieCategories;
        List<String> movieIds = new ArrayList<>();
        HashSet<String> intersection = new HashSet<>();

        LambdaQueryWrapper<Movie> queryWrapper = new LambdaQueryWrapper<>();

        if (searchDTO.getSearchKeyword() != null && !searchDTO.getSearchKeyword().isEmpty()) {
            queryWrapper.like(Movie::getTitle, searchDTO.getSearchKeyword());
        }

        if (searchDTO.getCategories() != null && !searchDTO.getCategories().isEmpty()) {
            boolean firstCategory = true;
            for (String categoryId : searchDTO.getCategories()) {
                movieCategories = movieCategoryMapper.selectList(new LambdaQueryWrapper<MovieCategory>()
                        .eq(MovieCategory::getCategoryId, categoryId));
                HashSet<String> tempMovieIds = new HashSet<>();
                for (MovieCategory movieCategory : movieCategories) {
                    tempMovieIds.add(movieCategory.getMovieId());
                }

                if (firstCategory) {
                    intersection.addAll(tempMovieIds);
                    firstCategory = false;
                } else {
                    intersection.retainAll(tempMovieIds);
                }
            }

            if (!intersection.isEmpty()) {
                queryWrapper.in(Movie::getId, intersection);
            } else {
                // 如果没有符合条件的 movieIds，返回空结果
                return R.success();
            }
        }
        Page<Movie> page = new Page<>(searchDTO.getCurrent(), searchDTO.getSize());
        IPage<MovieDTO> movies = movieMapper.selectSearch(page,queryWrapper);
        return R.success(movies);

    }
    @ApiOperation(value = "查看电影")
    @GetMapping("/{id}")
    public R<MovieDTO> getInfo(@PathVariable String id){
        MovieDTO movie = movieService.getById(id);
        return R.success(movie);

    }

    @RequiresPermissions("admin:manage")
    @ApiOperation(value = "添加电影")
    @PostMapping
    public R add(@RequestBody MovieDTO movieDTO){
        return movieService.save(movieDTO)?R.success():R.error();
    }

    @ApiOperation(value = "上传封面")
    @PostMapping("/upload/movie")
    public R<String> uploadMovie(@RequestParam("movieFile") MultipartFile movieFile){
        String url = FileUtil.saveMovie(movieFile, uploadMoviePath);
        return R.success(url);
    }
    @ApiOperation(value = "上传演员海报")
    @PostMapping("/upload/actors")
    public R uploadActors(MultipartFile[] actorFiles){
        return R.success();
    }

    @RequiresPermissions("admin:manage")
    @ApiOperation(value = "更新电影")
    @PutMapping("/{id}")
    public R update(@PathVariable String id,@RequestBody MovieDTO movieDTO){
        return movieService.update(id,movieDTO)?R.success():R.error();
    }

    @RequiresPermissions("admin:manage")
    @ApiOperation(value = "删除电影")
    @DeleteMapping("/{id}")
    public R delete(@PathVariable String id){
        return movieService.delete(id)?R.success():R.error();
    }



}
